package com.mdb.open.trade.facade;
/*
 * Copyright (C), 2017-2019 澳发科技(MDB)
 * FileName: MerchantInfoFacade.java
 * Author:   符楚
 * Date:     2019-10-12 14:06
 * History:
 * <author>          <time>          <version>          <desc>
 * 符楚               2019-10-12          V1.00             新建
 * -----------------------------------------------------------
 * 作者姓名           修改时间           版本号            描述
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.mdb.bc.api.data.ListResultEx;
import com.mdb.bc.api.data.PageVo;
import com.mdb.bc.api.data.ResultEx;
import com.mdb.bc.api.enums.NationalityEnum;
import com.mdb.bc.api.enums.OrderByEnum;
import com.mdb.bc.cache.sequence.util.SequenceGenerator;
import com.mdb.bc.database.mybatisplus.PageUtil;
import com.mdb.bc.utils.BeanConvertUtil;
import com.mdb.bc.utils.ObjectUtil;
import com.mdb.open.common.enums.TfSequenceEnum;
import com.mdb.open.common.enums.TradeWebErrorCodeEnum;
import com.mdb.open.common.enums.trade.status.*;
import com.mdb.open.common.enums.trade.type.*;
import com.mdb.open.trade.config.AccountingDateUtil;
import com.mdb.open.trade.domain.dto.customer.MerchantInfoDto;
import com.mdb.open.trade.domain.dto.customer.PMerchantInfoDto;
import com.mdb.open.trade.domain.dto.customer.QMerchantInfoDto;
import com.mdb.open.trade.domain.dto.product.SaveMerchantLimitDto;
import com.mdb.open.trade.domain.po.trade.CusAcc;
import com.mdb.open.trade.domain.po.trade.MerAcc;
import com.mdb.open.trade.domain.po.trade.MerchantInfo;
import com.mdb.open.trade.domain.vo.customer.MerchantInfoVo;
import com.mdb.open.trade.domain.vo.customer.SaveMerchantInfoVo;
import com.mdb.open.trade.feign.CustomerClient;
import com.mdb.open.trade.feign.dto.cus.*;
import com.mdb.open.trade.feign.vo.cus.CustAllDetailVo;
import com.mdb.open.trade.feign.vo.cus.CustBaseInfoVo;
import com.mdb.open.trade.feign.vo.cus.CustFileInfoVo;
import com.mdb.open.trade.service.trade.MerSubAccAutoIncrementInitializer;
import com.mdb.open.trade.service.trade.TfCusAccService;
import com.mdb.open.trade.service.trade.TfMerAccService;
import com.mdb.open.trade.service.trade.TfMerchantInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <br>
 * <br>
 *
 * @author 符楚
 * @Date 2019-10-12 14:06
 */
@Slf4j
@Component
public class MerchantInfoFacade {

    @Autowired
    TfMerchantInfoService tfMerchantInfoService;

    @Resource
    SequenceGenerator sequenceGenerator;

    @Autowired
    TfMerAccService tfMerAccService;

    @Autowired
    CustomerClient customerClient;

    @Autowired
    TfCusAccService tfCusAccService;

    @Autowired
    MerSubAccAutoIncrementInitializer merSubAccAutoIncrementInitializer;

    @Autowired
    AccountingDateUtil accountingDateUtil;

    @Autowired
    LimitFacade limitFacade;


    /**
     * 商户列表
     *
     * @param pageVo
     * @param qMerchantInfoDto
     * @param customerCode
     * @return
     */
    public ListResultEx<MerchantInfoVo> findByCondition(PageVo pageVo, QMerchantInfoDto qMerchantInfoDto, String customerCode) {

        //排序
        pageVo.setSort("create_time");
        pageVo.setOrder(OrderByEnum.DESC);

        LambdaQueryWrapper<MerchantInfo> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(MerchantInfo::getCustomerCode, customerCode);

        if (ObjectUtil.isNotEmpty(qMerchantInfoDto.getMerchantNo())) {
            queryWrapper.eq(MerchantInfo::getMerchantNo, qMerchantInfoDto.getMerchantNo());
        }

        if (ObjectUtil.isNotEmpty(qMerchantInfoDto.getMerchantNameCn())) {
            queryWrapper.like(MerchantInfo::getMerchantNameCn, qMerchantInfoDto.getMerchantNameCn());
        }

        if (ObjectUtil.isNotEmpty(qMerchantInfoDto.getMerchantNameEn())) {
            queryWrapper.like(MerchantInfo::getMerchantNameEn, qMerchantInfoDto.getMerchantNameEn());
        }

        IPage<MerchantInfo> iPage = tfMerchantInfoService.page(PageUtil.initPage(pageVo), queryWrapper);

        List<MerchantInfoVo> voList = BeanConvertUtil.convertList(iPage.getRecords(), info -> {

            MerchantInfoVo vo = new MerchantInfoVo();

            CustAndParentCodeDto custAndParentCodeDto = new CustAndParentCodeDto();
            custAndParentCodeDto.setCustomerCode(info.getMcustomerCode());
            if (!info.isDefaultStatus()) {
                custAndParentCodeDto.setParentCode(customerCode);
            }
            ResultEx<CustAllDetailVo> allInfoEx = customerClient.getCustAllInfo(custAndParentCodeDto);
            if (allInfoEx.isFailed() || ObjectUtil.isEmpty(allInfoEx.getData())) {
                return vo;
            }

            CustAllDetailVo detailVo = allInfoEx.getData();

            Map<FileTypeEnum, CustFileInfoVo> fileMap = detailVo.getFiles().stream().collect(Collectors.toMap(CustFileInfoVo::getFileType, e -> e));


            vo.setMerchantNo(info.getMerchantNo());
            vo.setMerchantType(info.getMerchantType());
            vo.setMerchantNameEn(info.getMerchantNameEn());
            vo.setMerchantNameCn(info.getMerchantNameCn());
            vo.setMerchantCertNumber(info.getMerchantCertNumber());
            vo.setBizLicenseFile(Optional.ofNullable(fileMap.get(FileTypeEnum.BIZ_LICENSE_FILE)).orElseGet(() -> new CustFileInfoVo()).getFile());
            vo.setPrincipalName(detailVo.getBaseInfo().getPersonName());
            vo.setPrincipalCertType(detailVo.getBaseInfo().getPersonCertType());
            vo.setPrincipalCertNumber(detailVo.getBaseInfo().getPersonCertCode());
            vo.setPrincipalCertFrontFile(Optional.ofNullable(fileMap.get(FileTypeEnum.ID_CARD_FRONT)).orElseGet(() -> new CustFileInfoVo()).getFile());
            vo.setPrincipalCertBackFile(Optional.ofNullable(fileMap.get(FileTypeEnum.ID_CARD_REVERSE)).orElseGet(() -> new CustFileInfoVo()).getFile());
            vo.setBusinessNature(detailVo.getBaseInfo().getBusinessNature());
            vo.setContactName(detailVo.getContracts().get(0).getName());
            vo.setContactPhoneCode(detailVo.getContracts().get(0).getPhoneCode());
            vo.setContactPhoneNumber(detailVo.getContracts().get(0).getPhoneNumber());
            vo.setContactEmail(detailVo.getContracts().get(0).getEmail());
            vo.setContactAddress(detailVo.getContracts().get(0).getAddress());
            vo.setMerchantStatus(info.getStatus());
            vo.setRiskStatus(info.getApproveStatus());
            vo.setMerchantPlatformAccount(info.getPlatformAcc());

            return vo;
        });


        return ListResultEx.ok(voList, iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    /**
     * 获取商户信息
     *
     * @param customerCode
     * @param merchantNo
     * @return
     */
    public MerchantInfoVo getMerchantInfo(String customerCode, String merchantNo) {

        MerchantInfoVo vo = new MerchantInfoVo();
        ResultEx<MerchantInfo> infoEx = tfMerchantInfoService.getMerchantInfo(customerCode, merchantNo);
        if (infoEx.isFailed() || ObjectUtil.isEmpty(infoEx.getData())) {
            return vo;
        }
        MerchantInfo info = infoEx.getData();

        CustAndParentCodeDto custAndParentCodeDto = new CustAndParentCodeDto();
        custAndParentCodeDto.setCustomerCode(info.getMcustomerCode());
        if (!info.isDefaultStatus()) {
            custAndParentCodeDto.setParentCode(customerCode);
        }

        ResultEx<CustAllDetailVo> allInfoEx = customerClient.getCustAllInfo(custAndParentCodeDto);
        if (allInfoEx.isFailed() || ObjectUtil.isEmpty(allInfoEx.getData())) {
            return vo;
        }

        CustAllDetailVo detailVo = allInfoEx.getData();

        Map<FileTypeEnum, CustFileInfoVo> fileMap = detailVo.getFiles().stream().collect(Collectors.toMap(CustFileInfoVo::getFileType, e -> e));


        vo.setMerchantNo(info.getMerchantNo());
        vo.setMerchantType(info.getMerchantType());
        vo.setMerchantNameEn(info.getMerchantNameEn());
        vo.setMerchantNameCn(info.getMerchantNameCn());
        vo.setMerchantCertNumber(info.getMerchantCertNumber());
        vo.setBizLicenseFile(Optional.ofNullable(fileMap.get(FileTypeEnum.BIZ_LICENSE_FILE)).orElseGet(() -> new CustFileInfoVo()).getFile());
        vo.setPrincipalName(detailVo.getBaseInfo().getPersonName());
        vo.setPrincipalCertType(detailVo.getBaseInfo().getPersonCertType());
        vo.setPrincipalCertNumber(detailVo.getBaseInfo().getPersonCertCode());
        vo.setPrincipalCertFrontFile(Optional.ofNullable(fileMap.get(FileTypeEnum.ID_CARD_FRONT)).orElseGet(() -> new CustFileInfoVo()).getFile());
        vo.setPrincipalCertBackFile(Optional.ofNullable(fileMap.get(FileTypeEnum.ID_CARD_REVERSE)).orElseGet(() -> new CustFileInfoVo()).getFile());
        vo.setBusinessNature(detailVo.getBaseInfo().getBusinessNature());
        vo.setContactName(detailVo.getContracts().get(0).getName());
        vo.setContactPhoneCode(detailVo.getContracts().get(0).getPhoneCode());
        vo.setContactPhoneNumber(detailVo.getContracts().get(0).getPhoneNumber());
        vo.setContactEmail(detailVo.getContracts().get(0).getEmail());
        vo.setContactAddress(detailVo.getContracts().get(0).getAddress());
        vo.setMerchantStatus(info.getStatus());
        vo.setRiskStatus(info.getApproveStatus());
        vo.setMerchantPlatformAccount(info.getPlatformAcc());

        return vo;

    }


    /**
     * 保存商户信息
     *
     * @param userId
     * @param customerCode
     * @return
     */
    public ResultEx<SaveMerchantInfoVo> save(MerchantInfoDto bo, String userName, String userId, String customerCode) {

        SaveMerchantInfoVo vo = new SaveMerchantInfoVo();


        int cnt = tfMerchantInfoService.count(new LambdaQueryWrapper<MerchantInfo>()
                .eq(MerchantInfo::getCustomerCode, customerCode)
                .eq(MerchantInfo::getMerchantCertNumber, bo.getMerchantCertNumber()));
        if (cnt > 0) {
            return ResultEx.fail(TradeWebErrorCodeEnum.MERCHANT_ALREADY_EXIST.getText());
        }

        CustAllInfoDto custAllInfoDto = new CustAllInfoDto();

        CustBaseInfoDto baseInfoDto = new CustBaseInfoDto();
        baseInfoDto.setCustomerType(bo.getMerchantType());
        baseInfoDto.setNameCn(bo.getMerchantNameCn());
        baseInfoDto.setNameEn(bo.getMerchantNameEn());
        baseInfoDto.setCreditCode(bo.getMerchantCertNumber());
        if (MerchantsTypeEnum.INDIVIDUAL.equals(bo.getMerchantType())) {
            baseInfoDto.setCreditType(CreditTypeEnum.ID_CARD);
            custAllInfoDto.setCreditType(CreditTypeEnum.ID_CARD);
        } else {
            custAllInfoDto.setCreditType(CreditTypeEnum.SOCIAL_CREDIT_CODE);
            baseInfoDto.setCreditType(CreditTypeEnum.SOCIAL_CREDIT_CODE);
        }
        baseInfoDto.setPersonName(bo.getPrincipalName());
        baseInfoDto.setPersonCertType(bo.getPrincipalCertType());
        baseInfoDto.setPersonCertCode(bo.getPrincipalCertNumber());
        baseInfoDto.setBusinessNature(bo.getBusinessNature());
        baseInfoDto.setCountry(NationalityEnum.CN);
        baseInfoDto.setDataChannel(com.mdb.enums.DataChannelEnum.OPEN);

        CustContractDto contractDto = new CustContractDto();
        contractDto.setName(bo.getContactName());
        contractDto.setPhoneCode(bo.getContactPhoneCode());
        contractDto.setPhoneNumber(bo.getContactPhoneNumber());
        contractDto.setEmail(bo.getContactEmail());
        contractDto.setAddress(bo.getContactAddress());

        custAllInfoDto.setBaseInfo(baseInfoDto);
        custAllInfoDto.setContracts(Lists.newArrayList(contractDto));

        CustFileInfoDto backFile = new CustFileInfoDto();
        backFile.setFile(bo.getPrincipalCertBackFile());
        backFile.setFileType(FileTypeEnum.ID_CARD_REVERSE);
        backFile.setFileName(FileTypeEnum.ID_CARD_REVERSE.getText());

        CustFileInfoDto frontFile = new CustFileInfoDto();
        frontFile.setFile(bo.getPrincipalCertFrontFile());
        frontFile.setFileType(FileTypeEnum.ID_CARD_FRONT);
        frontFile.setFileName(FileTypeEnum.ID_CARD_FRONT.getText());

        List<CustFileInfoDto> files = Lists.newArrayList(backFile, frontFile);

        if (ObjectUtil.isNotEmpty(bo.getBizLicenseFile())) {
            CustFileInfoDto bizFile = new CustFileInfoDto();
            bizFile.setFile(bo.getBizLicenseFile());
            bizFile.setFileType(FileTypeEnum.BIZ_LICENSE_FILE);
            bizFile.setFileName(FileTypeEnum.BIZ_LICENSE_FILE.getText());
            files.add(bizFile);
        }
        custAllInfoDto.setFiles(files);
        custAllInfoDto.setUserId(userId);
        custAllInfoDto.setUserName(userName);
        custAllInfoDto.setProduct(com.mdb.enums.product.ProductCodeEnum.TF01);
        custAllInfoDto.setParentCode(customerCode);
        custAllInfoDto.setRole(RoleTypeEnum.MERCHANT);
        custAllInfoDto.setCreditCode(bo.getMerchantCertNumber());


        ResultEx<CustBaseInfoVo> infoVoEx = customerClient.saveCustInfoDirect(custAllInfoDto);
        if (infoVoEx.isFailed() || ObjectUtil.isEmpty(infoVoEx.getData())) {
            return ResultEx.fail(infoVoEx.getRetMsg());
        }

        CustQueryDto queryDto = new CustQueryDto();
        queryDto.setCustomerCode(customerCode);
        ResultEx<CustBaseInfoVo> baseInfoEx = customerClient.getRelationCustomerInfoByParentCode(customerCode, RelationTypeEnum.BIZ_SUBJECT_COMPANY);
        if (baseInfoEx.isFailed() || ObjectUtil.isEmpty(baseInfoEx.getData())) {
            return ResultEx.fail(TradeWebErrorCodeEnum.MERCHANT_CREATE_ERROR.getText());
        }

        CusAcc cusAcc = tfCusAccService.getLimitOne(new LambdaQueryWrapper<CusAcc>()
                .eq(CusAcc::getCustomerCode, customerCode)
                .eq(CusAcc::getStatus, CusAccStatusEnum.NORMAL));
        if (ObjectUtil.isEmpty(cusAcc)) {
            return ResultEx.fail(TradeWebErrorCodeEnum.MERCHANT_CREATE_ERROR.getText());
        }

        String merchantAcc = cusAcc.getDaAcc() + sequenceGenerator.generator(TfSequenceEnum.MERCHANT_ACC_NO, merSubAccAutoIncrementInitializer);

        MerchantInfo saveMerchantInfo = new MerchantInfo();
        saveMerchantInfo.setCustomerCode(customerCode);
        saveMerchantInfo.setCustomerName(baseInfoEx.getData().getName());
        saveMerchantInfo.setMcustomerCode(infoVoEx.getData().getCustomerCode());
        saveMerchantInfo.setMerchantNo(sequenceGenerator.generator(TfSequenceEnum.MERCHANT_NO));
        saveMerchantInfo.setMerchantType(bo.getMerchantType());
        saveMerchantInfo.setMerchantNameCn(bo.getMerchantNameCn());
        saveMerchantInfo.setMerchantNameEn(bo.getMerchantNameEn());
        saveMerchantInfo.setMerchantCertNumber(bo.getMerchantCertNumber());
        saveMerchantInfo.setContractName(bo.getContactName());
        saveMerchantInfo.setContractPhone(bo.getContactPhoneCode() + bo.getContactPhoneNumber());
        saveMerchantInfo.setPlatformAcc(merchantAcc);
        saveMerchantInfo.setStatus(MerchantStatusEnum.NORMAL);
        saveMerchantInfo.setDefaultStatus(false);
        saveMerchantInfo.setDisableStatus(MerDisableStatusEnum.NORMAL);
        MerchantApproveStatusEnum approveStatus = MerchantApproveStatusEnum.PROCESSING;
        if (ObjectUtil.isNotEmpty(infoVoEx.getData().getCustRiskAccessStatusVo()) &&
                ObjectUtil.isNotEmpty(infoVoEx.getData().getCustRiskAccessStatusVo().getRejectChannel())) {
            log.info("准入状态:{}", infoVoEx.getData().getCustRiskAccessStatusVo());

            switch (infoVoEx.getData().getCustRiskAccessStatusVo().getRejectChannel()) {
                case AML:
                    if (ModelResultEnum.BLOCK.equals(infoVoEx.getData().getCustRiskAccessStatusVo().getAccessStatus())) {
                        approveStatus = MerchantApproveStatusEnum.AML_REJECT;
                        break;
                    }
                    if (ModelResultEnum.PASS.equals(infoVoEx.getData().getCustRiskAccessStatusVo().getAccessStatus())) {
                        approveStatus = MerchantApproveStatusEnum.AML_SUCCESS;
                        break;
                    }
                case ACCCESS_POLICY:
                    if (ModelResultEnum.BLOCK.equals(infoVoEx.getData().getCustRiskAccessStatusVo().getAccessStatus())) {
                        approveStatus = MerchantApproveStatusEnum.MODEL_REJECT;
                        break;
                    } else {
                        approveStatus = MerchantApproveStatusEnum.MODEL_APPROVED;
                        break;
                    }
            }
            saveMerchantInfo.setRemarks(infoVoEx.getData().getCustRiskAccessStatusVo().getModelRemark());
        }
        saveMerchantInfo.setApproveStatus(approveStatus);

        boolean saveFlag = tfMerchantInfoService.save(saveMerchantInfo);
        if (!saveFlag) {
            return ResultEx.fail(TradeWebErrorCodeEnum.MERCHANT_CREATE_ERROR.getText());
        }

        MerAcc saveMerAcc = new MerAcc();
        saveMerAcc.setCustomerCode(customerCode);
        saveMerAcc.setCustomerName(saveMerchantInfo.getCustomerName());
        saveMerAcc.setMerchantNo(saveMerchantInfo.getMerchantNo());
        saveMerAcc.setMcustomerCode(infoVoEx.getData().getCustomerCode());
        saveMerAcc.setMerchantName(saveMerchantInfo.getMerchantName());
        saveMerAcc.setBankClientNo(cusAcc.getBankClientNo());
        saveMerAcc.setDaAcc(cusAcc.getDaAcc());
        saveMerAcc.setSaAcc(cusAcc.getSaAcc());
        saveMerAcc.setPlatformAcc(merchantAcc);
        saveMerAcc.setStatus(MerAccStatusEnum.NORMAL);


        if (!tfMerAccService.save(saveMerAcc)) {
            return ResultEx.fail();
        }

        //创建商户
        SaveMerchantLimitDto limitDto = new SaveMerchantLimitDto();
        limitDto.setProdCode(com.mdb.enums.product.ProductCodeEnum.TF01.getValue());
        limitDto.setCustomerCode(customerCode);
        limitDto.setMerchantNo(infoVoEx.getData().getCustomerCode());
        limitDto.setMerchantType(bo.getMerchantType());
        limitDto.setMerchantName(saveMerchantInfo.getMerchantName());
        limitDto.setTotalBal(BigDecimal.ZERO);
        limitDto.setExpDate(accountingDateUtil.getAccountingDateTime().plusYears(99));
        limitDto.setRemark("创建商户，默认给额度");

        //调用产品服务
        ResultEx resultEx = limitFacade.saveMerchantLimit(limitDto);
        if (resultEx.isFailed()) {
            log.error("创建商户，默认给额度为0异常! Message: {}", resultEx.getRetMsg());
        }
        resultEx.assertSuccess();


        vo.setMerchantPlatformAccount(merchantAcc);
        vo.setMerchantNo(saveMerchantInfo.getMerchantNo());
        vo.setStatus(AvailableStatusEnum.convert(saveMerchantInfo.getStatus(), saveMerchantInfo.getApproveStatus()));
        return ResultEx.ok(vo);
    }



    /**
     * 编辑商户信息
     *
     * @param customerCode
     * @param merchantNo
     * @return
     */
    public ResultEx<MerchantInfoVo> edit(String userName, String userId, String customerCode, String merchantNo, PMerchantInfoDto bo) {

        MerchantInfo info = tfMerchantInfoService.getLimitOne(new LambdaQueryWrapper<MerchantInfo>()
                .eq(MerchantInfo::getCustomerCode, customerCode)
                .eq(MerchantInfo::getMerchantNo, merchantNo));
        if (ObjectUtil.isEmpty(info)) {
            return ResultEx.fail(TradeWebErrorCodeEnum.MERCHANT_STATUS_ILLEGAL.getText());
        }

        CustQueryDto custQueryDto = new CustQueryDto();
        custQueryDto.setCustomerCode(info.getMcustomerCode());
        ResultEx<CustBaseInfoVo> custBaseInfoEx = customerClient.getCustBaseInfo(custQueryDto);
        if (custBaseInfoEx.isFailed() || ObjectUtil.isEmpty(custBaseInfoEx.getData())) {
            return ResultEx.fail(TradeWebErrorCodeEnum.MERCHANT_STATUS_ILLEGAL.getText());
        }

        CustomerUpdateDto custAllInfoDto = new CustomerUpdateDto();

        CustBaseInfoDto baseInfoDto = new CustBaseInfoDto();
        baseInfoDto.setCustomerType(info.getMerchantType());
        baseInfoDto.setNameCn(bo.getMerchantNameCn());
        baseInfoDto.setNameEn(bo.getMerchantNameEn());
        baseInfoDto.setCreditCode(custBaseInfoEx.getData().getCreditCode());
        baseInfoDto.setCreditType(custBaseInfoEx.getData().getCreditType());
        baseInfoDto.setPersonName(bo.getPrincipalName());
        baseInfoDto.setPersonCertCode(bo.getPrincipalCertNumber());
        baseInfoDto.setBusinessNature(bo.getBusinessNature());

        CustContactDto contractDto = new CustContactDto();
        contractDto.setName(bo.getContactName());
        contractDto.setPhoneCode(bo.getContactPhoneCode());
        contractDto.setPhoneNumber(bo.getContactPhoneNumber());
        contractDto.setEmail(bo.getContactEmail());
        contractDto.setAddress(bo.getContactAddress());

        custAllInfoDto.setBaseInfo(baseInfoDto);
        custAllInfoDto.setContracts(Lists.newArrayList(contractDto));
        CustFileInfoDto backFile = new CustFileInfoDto();
        backFile.setFile(bo.getPrincipalCertBackFile());
        backFile.setFileType(FileTypeEnum.ID_CARD_REVERSE);
        backFile.setFileName(FileTypeEnum.ID_CARD_REVERSE.getText());

        CustFileInfoDto frontFile = new CustFileInfoDto();
        frontFile.setFile(bo.getPrincipalCertFrontFile());
        frontFile.setFileType(FileTypeEnum.ID_CARD_FRONT);
        frontFile.setFileName(FileTypeEnum.ID_CARD_FRONT.getText());

        List<CustFileInfoDto> files = Lists.newArrayList(backFile, frontFile);

        if (ObjectUtil.isNotEmpty(bo.getBizLicenseFile())) {
            CustFileInfoDto bizFile = new CustFileInfoDto();
            bizFile.setFile(bo.getBizLicenseFile());
            bizFile.setFileType(FileTypeEnum.BIZ_LICENSE_FILE);
            bizFile.setFileName(FileTypeEnum.BIZ_LICENSE_FILE.getText());
            files.add(bizFile);
        }

        custAllInfoDto.setFiles(files);
        custAllInfoDto.setUserId(userId);
        custAllInfoDto.setUserName(userName);
        custAllInfoDto.setCustomerCode(info.getMcustomerCode());

        ResultEx infoVoEx = customerClient.updateCustInfoGenerateOrder(custAllInfoDto);
        if (infoVoEx.isFailed()) {
            return ResultEx.fail(TradeWebErrorCodeEnum.MERCHANT_UPDATE_ERROR.getText());
        }

        CustQueryDto queryDto = new CustQueryDto();
        queryDto.setCustomerCode(customerCode);
        ResultEx<CustBaseInfoVo> baseInfoEx = customerClient.getRelationCustomerInfoByParentCode(customerCode, RelationTypeEnum.BIZ_SUBJECT_COMPANY);
        if (baseInfoEx.isFailed() || ObjectUtil.isEmpty(baseInfoEx.getData())) {
            return ResultEx.fail(TradeWebErrorCodeEnum.MERCHANT_UPDATE_ERROR.getText());
        }

        LambdaUpdateWrapper<MerchantInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MerchantInfo::getMcustomerCode, info.getMcustomerCode());

        MerchantInfo updateMerchant = new MerchantInfo();
        updateMerchant.setMerchantNameCn(bo.getMerchantNameCn());
        updateMerchant.setMerchantNameEn(bo.getMerchantNameEn());
        updateMerchant.setContractPhone(bo.getContactPhoneCode() + bo.getContactPhoneNumber());
        updateMerchant.setContractName(bo.getContactName());

        tfMerchantInfoService.update(updateMerchant, updateWrapper);

        MerchantInfoVo vo = new MerchantInfoVo();

        CustAndParentCodeDto custAndParentCodeDto = new CustAndParentCodeDto();
        custAndParentCodeDto.setCustomerCode(info.getMcustomerCode());
        if (!info.isDefaultStatus()) {
            custAndParentCodeDto.setParentCode(customerCode);
        }

        ResultEx<CustAllDetailVo> allInfoEx = customerClient.getCustAllInfo(custAndParentCodeDto);
        if (allInfoEx.isFailed() || ObjectUtil.isEmpty(allInfoEx.getData())) {
            return ResultEx.ok(vo);
        }

        CustAllDetailVo detailVo = allInfoEx.getData();

        Map<FileTypeEnum, CustFileInfoVo> fileMap = detailVo.getFiles().stream().collect(Collectors.toMap(CustFileInfoVo::getFileType, e -> e));


        vo.setMerchantNo(info.getMerchantNo());
        vo.setMerchantType(info.getMerchantType());
        vo.setMerchantNameEn(info.getMerchantNameEn());
        vo.setMerchantNameCn(info.getMerchantNameCn());
        vo.setMerchantCertNumber(info.getMerchantCertNumber());
        vo.setBizLicenseFile(Optional.ofNullable(fileMap.get(FileTypeEnum.BIZ_LICENSE_FILE)).orElseGet(() -> new CustFileInfoVo()).getFile());
        vo.setPrincipalName(detailVo.getBaseInfo().getPersonName());
        vo.setPrincipalCertType(detailVo.getBaseInfo().getPersonCertType());
        vo.setPrincipalCertNumber(detailVo.getBaseInfo().getPersonCertCode());
        vo.setPrincipalCertFrontFile(Optional.ofNullable(fileMap.get(FileTypeEnum.ID_CARD_FRONT)).orElseGet(() -> new CustFileInfoVo()).getFile());
        vo.setPrincipalCertBackFile(Optional.ofNullable(fileMap.get(FileTypeEnum.ID_CARD_REVERSE)).orElseGet(() -> new CustFileInfoVo()).getFile());
        vo.setBusinessNature(detailVo.getBaseInfo().getBusinessNature());
        vo.setContactName(detailVo.getContracts().get(0).getName());
        vo.setContactPhoneCode(detailVo.getContracts().get(0).getPhoneCode());
        vo.setContactPhoneNumber(detailVo.getContracts().get(0).getPhoneNumber());
        vo.setContactEmail(detailVo.getContracts().get(0).getEmail());
        vo.setContactAddress(detailVo.getContracts().get(0).getAddress());
        vo.setMerchantStatus(info.getStatus());
        vo.setRiskStatus(info.getApproveStatus());
        vo.setMerchantPlatformAccount(info.getPlatformAcc());

        return ResultEx.ok(vo);
    }

}
